package com.dzt.androidframework.json;

import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;

import com.dzt.androidframework.R;
import com.dzt.androidframework.activity.ActivityTitle;
import com.dzt.androidframework.utils.JCommonKit;
import com.dzt.androidframework.utils.JLogKit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CityActivity extends ActivityTitle {

	@ViewInject(R.id.elv_province)
	private ExpandableListView expandableList;
	private SimpleExpandableListAdapter selaAdapter;
	public List<Map<String, String>> strProvinces;
	public List<List<Map<String, String>>> strCities;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_city;
	}

	@Override
	protected void initParams() {
		setTitleView(R.string.text_city_select);
		strProvinces = new ArrayList<>();
		strCities = new ArrayList<>();
		analysisJson();
		selaAdapter = new SimpleExpandableListAdapter(context,
				strProvinces, R.layout.item_group,
				new String[]{"group"}, new int[]{R.id.tv_group},
				strCities, R.layout.item_child,
				new String[]{"child"}, new int[]{R.id.tv_child});
		expandableList.setAdapter(selaAdapter);
		// 设置item点击的监听器
		expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
										int groupPosition, int childPosition, long id) {

				Map<String, String> map = (HashMap<String, String>) selaAdapter
						.getChild(groupPosition, childPosition);
				String city = map.get("child");
				JLogKit.getInstance().i("city = " + city);
				return false;
			}
		});
	}

	@Override
	protected void initData(Bundle savedInstanceState) {

	}

	private void analysisJson() {
		strProvinces.clear();
		strCities.clear();
		String json = JCommonKit.getJsonString(context, "area.json");
		try {
			JSONObject dataJson = new JSONObject(json);
			JSONArray provinces = dataJson.getJSONArray("provinces");
			for (int i = 0; i < provinces.length(); i++) {
				JSONObject province = provinces.getJSONObject(i);
				String pro = province.getString("province");
				Map<String, String> group = new HashMap<>();

				group.put("group", pro);
				strProvinces.add(group);
				JSONArray cities = province.getJSONArray("cities");
				List<Map<String, String>> childes = new ArrayList<>();
				for (int j = 0; j < cities.length(); j++) {
					Map<String, String> child = new HashMap<>();
					child.put("child", cities.getString(j));
					childes.add(child);
				}
				strCities.add(childes);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected String[] initPermissions() {
		return new String[0];
	}
}
